import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import ElementPlus from 'unplugin-element-plus/vite'
import path from 'path'


export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), ['VITE_', 'APP_'])

  return {
    build: {
      outDir: 'dist',
      assetsDir: 'assets',
      minify: 'terser',
      sourcemap: "inline",
    },
    envPrefix: ['VITE_', 'APP_'], // 扩展环境变量前缀
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/assets/styles/element/index.scss"  as *;`,
          charset: false // 修复 @charset 警告
        }
      }
    },
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver({ importStyle: 'sass' })],
        imports: ['vue', 'vue-router'], // 常用库自动导入
        dts: 'types/auto-imports.d.ts',
        eslintrc: { enabled: true } // 生成 ESLint 配置
      }),
      Components({
        resolvers: [
          ElementPlusResolver({
            importStyle: 'sass',
            directives: true // 自动导入指令
          })
        ],
        dts: 'types/components.d.ts',
        types: [{ from: 'vue-router', names: ['RouterLink', 'RouterView'] }]
      }),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
        symbolId: 'icon-[name]',

      }),
      ElementPlus({
        useSource:false, // 生产环境关闭源码导入
      }),


    ],
    server: {
      host: '0.0.0.0',
      port: 80,
      strictPort: true, // 端口占用直接报错
      proxy: {
        '/app-api': {
          target: env.VITE_API_BASE_URL,

          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/app-api/, ''),

        }
      }
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
      },
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json'] // 扩展名优先级
    },

    optimizeDeps: { // 预构建优化
      include: ['vue', 'element-plus', 'vue-router'],
      exclude: ['vue-demi']
    }
  }
})
